package com.huaxin.hxcloud.activity;

import android.content.Intent;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.model.LatLng;
import com.huaxin.common.BaseActivity;
import com.huaxin.common.BaseApp;
import com.huaxin.common.Constants;
import com.huaxin.common.Entity.ArrangeWorkTask;
import com.huaxin.common.Entity.ArrangeWorkTaskDTO;
import com.huaxin.common.Entity.BaseDTO;
import com.huaxin.common.Global;
import com.huaxin.common.tools.HxTransmitRequestHelper;
import com.huaxin.common.utils.SDKBug;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.pulltorefresh.CustomHeaderLayout;
import com.huaxin.common.view.pulltorefresh.PullToRefreshBase;
import com.huaxin.common.view.pulltorefresh.extras.recyclerview.PullToRefreshRecyclerView;
import com.huaxin.hxcloud.R;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.ButterKnife;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by Administrator on 2016/9/28.
 */
public class ArrangeTaskListActivity extends BaseActivity implements View.OnClickListener, PullToRefreshBase.OnRefreshListener2 {

    @BindString(R.string.worktask_info)
    String infoFormat;


    RecyclerView listView;
    ArrayList _datas = new ArrayList<>();
    ArrangeTaskAdapter adapter;
    int                _finishNum;
    int                _unFinishNum;
    @BindView(R.id.more)
    ImageView                 more;
    @BindView(R.id.toolbar)
    Toolbar                   toolbar;
    @BindView(R.id.pull_view)
    PullToRefreshRecyclerView pullView;
    @BindView(R.id.content)
    FrameLayout               content;
    private int ret_pos;
    private int firstComeIn=0;


    @Override
    protected int getContentViewId() {
        return R.layout.activity_arrange_worktask_list;
    }

    @Override
    protected int getLoadFrameId() {
        return R.id.content;
    }

    @Override
    public void requestData() {
//        ApiRequestData(LOADING, null);
//        requestAddress(BaseApp.getLatLng());
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (firstComeIn == 0){
            ApiRequestData(LOADING, null);
        }else{
            ApiRequestData(LOAD_SUCCESS, null);
        }
        firstComeIn++;
        requestAddress(BaseApp.getLatLng());
    }

    /**
     * 提交经纬度
     *
     * @param latLng
     */
    private void requestAddress(LatLng latLng) {
        if (latLng == null) {
            return;
        }
        Call<BaseDTO> call = HxTransmitRequestHelper.getRequestApi().commitLngLat(latLng.longitude, latLng.latitude);
        call.enqueue(new Callback<BaseDTO>() {
            @Override
            public void onResponse(Call<BaseDTO> call, Response<BaseDTO> response) {
                Log.d(TAG, "onResponse:---> " + response.isSuccessful());
            }

            @Override
            public void onFailure(Call<BaseDTO> call, Throwable t) {
                Log.d(TAG, "onResponse: " + t);
            }
        });

    }

    private void ApiRequestData(int status, final PullToRefreshBase refreshView) {
        if (refreshView == null) {
            updateLoadStatus(status);
        }
        Call<ArrangeWorkTaskDTO> call = HxTransmitRequestHelper.getRequestApi().getArrangeTaskList();
        // autoClose(call);
        Log.d(TAG, "ApiRequestData: --->" + call.request().url());

        call.enqueue(new Callback<ArrangeWorkTaskDTO>() {
            @Override
            public void onResponse(Call<ArrangeWorkTaskDTO> call, Response<ArrangeWorkTaskDTO>
                    response) {
                ArrangeWorkTaskDTO arrangeWorkTaskDTO = response.body();

                Log.d(TAG, "onResponse:Data -1-->" + response.toString());
                Log.d(TAG, "onResponse:Data -2-->" + call.isExecuted());
                Log.d(TAG, "onResponse:Data -3-->" + response.isSuccessful());
                Log.d(TAG, "onResponse:Data -4-->" + response.message());
                Log.d(TAG, "onResponse:Data -5-->" + response.code());

                if (arrangeWorkTaskDTO != null && arrangeWorkTaskDTO.isSuccessful()) {
                    _finishNum = arrangeWorkTaskDTO.getFinishNum();
                    _unFinishNum = arrangeWorkTaskDTO.getNoFinishNum();
                    _datas.clear();
                    List<ArrangeWorkTask> temp = arrangeWorkTaskDTO.getTaskList();
                    _datas.addAll(temp);

                    adapter.handleExtraView();
                    adapter.notifyDataSetChanged();
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_SUCCESS);
                    } else {
                        refreshView.onRefreshComplete();
                    }

                } else {
                    if (refreshView == null) {
                        updateLoadStatus(LOAD_ERROR);
                    } else {
                        refreshView.onRefreshComplete();
                    }
                }
            }

            @Override
            public void onFailure(Call<ArrangeWorkTaskDTO> call, Throwable t) {
                Log.d(TAG, "onFailure:Data --->" + t);
                if (refreshView == null) {
                    updateLoadStatus(LOAD_FAILURE);
                } else {
                    refreshView.onRefreshComplete();
                    ToastUtil.showToast("网络故障");
                }
            }
        });
    }


    private void setFormatString(TextView textView, String format, Object... args) {
        String s = String.format(format, args);
        SpannableString styledText = new SpannableString(s);
        int position = 0, length = 0;
        for (Object arg : args) {
            if (arg instanceof String) {
                position = s.indexOf((String) arg, position + length);
                length = ((String) arg).length();
                styledText.setSpan(new RelativeSizeSpan(1.3f), position, position + length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        textView.setText(styledText, TextView.BufferType.SPANNABLE);
    }

    @Override
    public void initView() {
        super.initView();
        setSupportActionBar(toolbar);
        toolbar.setTitle("工单");
        more.setImageResource(R.drawable.icon_history_f);
        more.setOnClickListener(this);
        //        pullView.setLayoutVisibilityEnable(false);
        pullView.setHeaderLayout(new CustomHeaderLayout(this));
        pullView.setOnRefreshListener(this);
        listView = pullView.getRefreshableView();
        listView.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL,
                false));
        adapter = new ArrangeTaskAdapter();
        listView.setAdapter(adapter);


    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.more:
                startActivity(new Intent(ArrangeTaskListActivity.this,
                        ArrangeTaskHistoryActivity.class));
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == Constants.RET_AT_STATE) {
                int isPause = data.getIntExtra(Constants.IK_TASK_PAUSE, 0);
//                ((ArrangeWorkTask) _datas.get(ret_pos)).setIsSuspended(isPause);
//                adapter.notifyItemChanged(ret_pos);
                int state = data.getIntExtra(Constants.IK_AT_STATE, 0);
                Log.e("lwjing","onActivityResult refresh="+state+" pause="+isPause);
                if (state == 2) {
                    _datas.remove(ret_pos);
                    adapter.handleExtraView();
                    adapter.notifyDataSetChanged();
                } else {
                    ((ArrangeWorkTask) _datas.get(ret_pos)).setState(state);
                    adapter.notifyItemChanged(ret_pos);
                }

            }
        }
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase refreshView) {
        ApiRequestData(LOAD_SUCCESS, refreshView);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase refreshView) {
        refreshView.onRefreshComplete();
    }


    public class ArrangeTaskAdapter extends RecyclerView.Adapter {

        private static final int TYPE_ITEM   = 0x00;
        private static final int TYPE_HEADER = 0x01;
        private static final int TYPE_FOOTER = 0x02;
        private static final int TYPE_EMPTY  = 0x03;


        /**
         * add before notifyDataSetChanged!
         */
        public void handleExtraView() {

            int length = _datas.size();
            for (int i = 0; i < length; i++) {
                if (getItemViewType(i) != TYPE_ITEM) {
                    _datas.remove(i);
                    i--;
                    length--;
                }
            }
            if (_datas.isEmpty()) {
                _datas.add(Constants.EMPTY_VIEW);
            } else {
                _datas.add(Constants.FOOTER_VIEW);
            }
            _datas.add(0, Constants.HEADER_VIEW);

        }

        @Override
        public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            if (viewType == TYPE_ITEM) {
                return new MyViewHolder(mInflater.inflate(R.layout.item_arrange_task, parent, false));
            } else if (viewType == TYPE_EMPTY) {
                return new EmptyHolder(mInflater.inflate(R.layout.item_empty_face_top2, parent, false));
            } else if (viewType == TYPE_HEADER) {
                return new HeaderHolder(mInflater.inflate(R.layout.item_arrange_task_header, parent, false));
            } else if (viewType == TYPE_FOOTER) {
                return new FooterHolder(mInflater.inflate(R.layout.item_footer, parent, false));
            }
            return null;
        }

        @Override
        public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {

            if (getItemViewType(position) == TYPE_ITEM) {
                ((MyViewHolder) holder).update(position);
            } else if (getItemViewType(position) == TYPE_EMPTY) {
                ((EmptyHolder) holder).update(position);
            } else if (getItemViewType(position) == TYPE_HEADER) {
                ((HeaderHolder) holder).update(position);
            } else if (getItemViewType(position) == TYPE_FOOTER) {
                ((FooterHolder) holder).update(position);
            }

        }

        @Override
        public int getItemViewType(int position) {
            if (_datas.get(position) instanceof ArrangeWorkTask) {
                return TYPE_ITEM;
            } else if (_datas.get(position).equals(Constants.HEADER_VIEW)) {
                return TYPE_HEADER;
            } else if (_datas.get(position).equals(Constants.FOOTER_VIEW)) {
                return TYPE_FOOTER;
            } else if (_datas.get(position).equals(Constants.EMPTY_VIEW)) {
                return TYPE_EMPTY;
            }
            return super.getItemViewType(position);
        }

        @Override
        public int getItemCount() {
            return _datas == null ? 0 : _datas.size();
        }


        public class EmptyHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.tv_tip)
            TextView tvTip;
            View itemView;

            public EmptyHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;

            }

            public void update(int position) {
                //ImageMarkUtil.setWaterMarkTextBg(itemView,ArrangeTaskListActivity.this,"暂无数据");
                tvTip.setText("暂无工单！");
            }
        }

        public class HeaderHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.company)
            TextView company;
            @BindView(R.id.info)
            TextView info;

            public HeaderHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
            }

            public void update(int position) {
                if (Global.user != null) {
                    company.setText(Global.user.getCompany());
                }
                setFormatString(info, infoFormat, _finishNum, _unFinishNum);
            }

        }

        public class FooterHolder extends RecyclerView.ViewHolder {

            public FooterHolder(View itemView) {
                super(itemView);
            }

            public void update(int position) {
            }
        }

        public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
            @BindView(R.id.area)
            TextView area;
            @BindView(R.id.title)
            TextView title;
            @BindView(R.id.type)
            TextView type;
            @BindView(R.id.task_code_item)
            TextView taskCodeItem;
            @BindView(R.id.task_code)
            TextView taskCode;
            @BindView(R.id.worker_item)
            TextView workerItem;
            @BindView(R.id.worker)
            TextView worker;
            @BindView(R.id.start_date)
            TextView startDate;
            @BindView(R.id.plan)
            TextView plan;
            @BindView(R.id.divider)
            View     divider;
            @BindView(R.id.finish_date)
            TextView finishDate;
            @BindView(R.id.state)
            TextView state;
//            @BindView(R.id.tv_stop_task)
//            TextView tv_stop_task;

            View itemView;
            int  position;

            public MyViewHolder(View itemView) {
                super(itemView);
                ButterKnife.bind(this, itemView);
                this.itemView = itemView;
            }


            public void update(int position) {
                this.position = position;
                ArrangeWorkTask data = (ArrangeWorkTask) _datas.get(position);
                if (data.getRealStartDate() != 0) {
                    startDate.setText(("开始时间：" + dateFormat(data.getRealStartDate())));
                    plan.setVisibility(View.GONE);
                } else {
                    startDate.setText(("开始时间：" + dateFormat(data.getPlanStartDate())));
                    plan.setVisibility(View.VISIBLE);
                }
                if (data.getRealFinishDate() != 0) {
                    finishDate.setText(("完成日期：" + dateFormat(data.getRealFinishDate())));
                } else {
                    finishDate.setText(("截止日期：" + dateFormat(data.getPlanFinishDate())));
                }

                taskCode.setText(data.getArrangeTaskCode());
                title.setText(data.getTitle());
                area.setText(data.getOrgName());
                worker.setText(StringUtils.toString(data.getWorkers()));
                //0表示派工单没暂停，1表示派工单暂停
//                if (data.getIsSuspended() == 0) {
//                    tv_stop_task.setText("");
//                    tv_stop_task.setVisibility(View.INVISIBLE);
//                } else if (data.getIsSuspended() == 1) {
//                    tv_stop_task.setText("工单已暂停");
//                    tv_stop_task.setVisibility(View.VISIBLE);
//                }
                //taskType ：0 厂站巡检 1其他派工 2 厂内巡检
                String taskType = "";
                switch (data.getTaskType()) {
                    case 0:
                        taskType = "巡";
                        break;
                    case 1:
                        taskType = "修";
                        break;
                    case 2:
                        taskType = "内";
                        break;
                        default:
                            break;
                }
                type.setText(taskType);

                switchState(data.getState(), data.getProgress());
                itemView.setOnClickListener(this);
               // tv_stop_task.setOnClickListener(this);

            }

            private void switchState(int _state, float process) {
                if (_state == 0) {
                    title.setTextColor(ContextCompat.getColor(ArrangeTaskListActivity.this, R
                            .color.color_data11));
                    //                    itemView.setBackgroundResource(R.drawable.bg_arrange_worktask_item0);
                    SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_arrange_worktask_item0);
                    //                    area.setBackgroundResource(R.drawable.bg_bottom_round0);
                    SDKBug.setBackgroundResourceWithPadding(area, R.drawable.bg_bottom_round0);
                    state.setText("未开始");
                    state.setTextColor(ContextCompat.getColor(ArrangeTaskListActivity.this, R.color.color_data11));
                    //                    state.setBackgroundResource(R.drawable.bg_progress0);
                    SDKBug.setBackgroundResourceWithPadding(state, R.drawable.bg_progress0);
                } else if (_state == 1) {
                    title.setTextColor(ContextCompat.getColor(ArrangeTaskListActivity.this, R
                            .color.color_data12));
                    //                    itemView.setBackgroundResource(R.drawable.bg_arrange_worktask_item1);
                    SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_arrange_worktask_item1);
                    SDKBug.setBackgroundResourceWithPadding(area, R.drawable.bg_bottom_round1);
                    //                    area.setBackgroundResource(R.drawable.bg_bottom_round1);
                    //                    state.setText("进行中");
                    state.setText(((int) (process * 100) + "%"));
                    state.setTextColor(ContextCompat.getColor(ArrangeTaskListActivity.this, R.color.color_data12));
                    //                    state.setBackgroundResource(R.drawable.bg_progress1);
                    SDKBug.setBackgroundResourceWithPadding(state, R.drawable.bg_progress1);
                } else if (_state == 2) {
                    title.setTextColor(ContextCompat.getColor(ArrangeTaskListActivity.this, R
                            .color.color_data));
                    //                    itemView.setBackgroundResource(R.drawable.bg_arrange_worktask_item2);
                    SDKBug.setBackgroundResourceWithPadding(itemView, R.drawable.bg_arrange_worktask_item2);
                    //                    area.setBackgroundResource(R.drawable.bg_bottom_round2);
                    SDKBug.setBackgroundResourceWithPadding(area, R.drawable.bg_bottom_round2);
                    state.setText("");
                    //                    state.setBackgroundResource(R.drawable.icon_done);
                    SDKBug.setBackgroundResourceWithPadding(state, R.drawable.icon_done);
                }

            }

            @Override
            public void onClick(View v) {
                ret_pos = position;
                ArrangeWorkTask data = (ArrangeWorkTask) _datas.get(position);
                switch (v.getId()) {
                    case R.id.tv_stop_task:
                        break;
                    default:
                        WorkTaskListActivity.start(ArrangeTaskListActivity.this, data);
                }
            }
        }
    }

}